﻿using System;
using System.Reflection;
using Components.Configuration;

namespace Components.Data.Fields
{
  internal class FieldFactory
  {
    public virtual Field Create(String type)
    {
      FieldReference fieldReference = ConfigurationManager.Instance.FieldReferences[type];

      String typeInfo = fieldReference.Type;

      if (!(!String.IsNullOrEmpty(typeInfo) && typeInfo.Contains(",") && !typeInfo.StartsWith(",") && !typeInfo.EndsWith(",")))
        return null;

      String assemblyName = typeInfo.Substring((typeInfo.IndexOf(",") + 1)).Trim();
      if (String.IsNullOrEmpty(assemblyName))
        return null;

      String typeName = typeInfo.Substring(0, typeInfo.IndexOf(",")).Trim();
      if (String.IsNullOrEmpty(typeName))
        return null;

      Assembly loadedAssembly = Assembly.Load(assemblyName);
      if (loadedAssembly == null)
        return null;


      Type loadedType = loadedAssembly.GetType(typeName);
      if (loadedType == null)
        return null;

      Object loadedObject = Activator.CreateInstance(loadedType);

      if (!(loadedObject is Field))
        return null;

      Field field = loadedObject as Field;
      field.ID = new Guid();
      return field;
    }
  }
}